package com.sofwin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sofwin.dto.UserDto;
import com.sofwin.mapper.SysUserMapper;
import com.sofwin.pojo.SysUser;
import com.sofwin.pojo.SysUserExample;
import com.sofwin.service.UserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.assertj.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * ClassName: UserServiceImpl
 * Description: TODO
 * date: 2022/4/26 3:21 下午
 *
 * @author andyliu
 * @qq 115176513
 * @since JDK 1.8
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper mapper;
    @Override
    public PageInfo<UserDto> queryUsers(SysUser user, Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber,pageSize);
        List<UserDto> users = mapper.selectUsers(user);
        return new PageInfo<>(users);
    }

    @Override
    public SysUser queryById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean saveOrUpdate(SysUser user) {
        if(user.getSalt()==null || "".equals(user.getSalt())){
            user.setSalt(UUID.randomUUID().toString());
        }
        if(user.getUserId()!=null){
            user.setUpdateTime(DateUtil.formatAsDatetime(new Date()));
            return mapper.updateByPrimaryKeySelective(user)==1?true:false;
        }
        SimpleHash simpleHash = new SimpleHash("md5", user.getPassword(), user.getSalt(), 1);
        String s = simpleHash.toString();

        user.setPassword(s);
        user.setCreatTime(DateUtil.formatAsDatetime(new Date()));
        return mapper.insertSelective(user)==1?true:false;
    }

    @Override
    public boolean removeById(Integer id) {
        return mapper.deleteByPrimaryKey(id)==1?true:false;
    }

    @Override
    public boolean removeByIds(Integer[] ids) {
        int num=0;
        for(Integer id:ids){
            if(removeById(id)){
                num++;
            }
        }
        return num==ids.length?true:false;
    }

    @Override
    public SysUser checkLogin(String loginName) {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(loginName);
        List<SysUser> users = mapper.selectByExample(example);
        if(users!=null && users.size()==1){
            return users.get(0);
        }
        return null;
    }
}
